package com.tgpay.iot.controller;

import com.tgpay.iot.model.ApiResponse;
import com.tgpay.iot.service.UpstreamApiService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 设备控制器 - 代理前端请求到上游API
 */
@RestController
@RequestMapping("/api")
@RequiredArgsConstructor
@Slf4j
@CrossOrigin(origins = "*")
public class DeviceController {
    
    private final UpstreamApiService upstreamApiService;
    
    /**
     * 获取设备列表
     */
    @GetMapping("/devices")
    public ApiResponse<Object> getDevices() {
        try {
            Object response = upstreamApiService.getDevices();
            return ApiResponse.success(response);
        } catch (Exception e) {
            log.error("获取设备列表失败", e);
            return ApiResponse.error("获取设备列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取设备详情
     */
    @GetMapping("/devices/{imei}")
    public ApiResponse<Object> getDeviceDetail(@PathVariable String imei) {
        try {
            Object response = upstreamApiService.getDeviceDetail(imei);
            return ApiResponse.success(response);
        } catch (Exception e) {
            log.error("获取设备详情失败，IMEI：{}", imei, e);
            return ApiResponse.error("获取设备详情失败：" + e.getMessage());
        }
    }
    
    /**
     * 启动充电
     */
    @PostMapping("/devices/{imei}/ports/{portId}/start")
    public ApiResponse<Object> startCharging(
            @PathVariable String imei,
            @PathVariable String portId,
            @RequestBody Map<String, Object> requestBody) {
        try {
            // 处理充电参数：如果是按时间充电(chargeType=3)，需要将分钟转换为秒数
            Object chargeType = requestBody.get("chargeType");
            Object chargeParam = requestBody.get("chargeParam");
            
            if (chargeType != null && chargeParam != null) {
                int type = Integer.parseInt(chargeType.toString());
                if (type == 3) { // 按时间充电
                    int minutes = Integer.parseInt(chargeParam.toString());
                    int seconds = minutes * 60; // 转换为秒数
                    requestBody.put("chargeParam", seconds);
                    log.info("按时间充电：将{}分钟转换为{}秒", minutes, seconds);
                }
            }
            
            Object response = upstreamApiService.startCharging(imei, portId, requestBody);
            return ApiResponse.success(response);
        } catch (Exception e) {
            log.error("启动充电失败，IMEI：{}，端口：{}", imei, portId, e);
            return ApiResponse.error("启动充电失败：" + e.getMessage());
        }
    }
    
    /**
     * 停止充电
     */
    @PostMapping("/devices/{imei}/ports/{portId}/stop")
    public ApiResponse<Object> stopCharging(
            @PathVariable String imei,
            @PathVariable String portId,
            @RequestBody Map<String, Object> requestBody) {
        try {
            Object response = upstreamApiService.stopCharging(imei, portId, requestBody);
            return ApiResponse.success(response);
        } catch (Exception e) {
            log.error("停止充电失败，IMEI：{}，端口：{}", imei, portId, e);
            return ApiResponse.error("停止充电失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取设备状态
     */
    @GetMapping("/devices/{imei}/status")
    public ApiResponse<Object> getDeviceStatus(@PathVariable String imei) {
        try {
            Object response = upstreamApiService.getDeviceStatus(imei);
            return ApiResponse.success(response);
        } catch (Exception e) {
            log.error("获取设备状态失败，IMEI：{}", imei, e);
            return ApiResponse.error("获取设备状态失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取充电状态
     */
    @GetMapping("/devices/{imei}/ports/{portId}/status")
    public ApiResponse<Object> getChargingStatus(
            @PathVariable String imei,
            @PathVariable String portId,
            @RequestParam(required = false) String orderNo) {
        try {
            Object response = upstreamApiService.getChargingStatus(imei, portId, orderNo);
            return ApiResponse.success(response);
        } catch (Exception e) {
            log.error("获取充电状态失败，IMEI：{}，端口：{}", imei, portId, e);
            return ApiResponse.error("获取充电状态失败：" + e.getMessage());
        }
    }
}